<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>智慧校园</title>
    <link
      rel="stylesheet"
      href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css"
    />
    <link rel="stylesheet" href="./css/index.css" />
    <style>
      html,
      body,
      #container {
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <div class="info">点击地图标注热门地点</div>
  </body>
  <script src="https://webapi.amap.com/maps?v=2.0&key=3436ed8e83b40d5bb4f61e40fb8d6369"></script>
  <script src="./js/index.js"></script>
  <script>
    // 初始化地图
    var map = new AMap.Map("container", {
      viewMode: "3D", // 默认使用 2D 模式，如果希望使用带有俯仰角的 3D 模式，请设置 viewMode: '3D'
      zoom: 16, // 初始化地图层级
      center: [116.397428, 39.90923], // 初始化地图中心点
      patch: 45,
    });

    // 添加地图控件
    AMap.plugin(
      [
        "AMap.ToolBar",
        "AMap.Scale",
        "AMap.ControlBar",
        "AMap.Geolocation",
        "AMap.GeoJSON",
      ],
      function () {
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.ControlBar());
        map.addControl(new AMap.Geolocation());
      }
    );

    // 定义一个全局变量，保存geojson
    var geojson = new AMap.GeoJSON({
      geoJSON: null,
    });

    // 导入数据
    var data = getData();
    data.length != 0 ? geojson.importData(data) : "";
    geojson.eachOverlay(function(item){
      item.on('click',function(e){
        var ext = item.getExtData()
        ext._geoJsonProperties.click = ++ext._geoJsonProperties.click
        saveData(geojson.toGeoJSON());
      })
    })

    map.add(geojson);

    // 添加点位
    map.on("click", function (e) {
      var marker = new AMap.Marker({
        position: e.lnglat,
        extData:{
          _geoJsonProperties:{
            gid:geojson.getOverlays().length+1,
            click:0,
          }
        }
      });

      // 给覆盖物添加点击事件
      marker.on("click", function (e) {
        var ext = marker.getExtData()
        ext._geoJsonProperties.click = ++ext._geoJsonProperties.click
        saveData(geojson.toGeoJSON());
      });

      // map.add(marker)
      // 通过geoJSON对象来管理覆盖物
      geojson.addOverlay(marker);

      // 保存数据
      saveData(geojson.toGeoJSON());
    });
  </script>
</html>
